#include "cloop.h"

uint8_t cloop_init(cloop_t *cloop_in,uint8_t *buf_in,uint16_t len_in){
    cloop_in->Deep = len_in;
    cloop_in->buf = buf_in;
    for (int i = 0; i < len_in; i++){
        cloop_in->buf[i]=0;
    }
#ifdef CLOOP_USE_MUTEX
    cloop_in->mutex = CLOOP_MUTEX_UNLOCK ;
#endif
    cloop_in->opration_protect = 0 ;
    cloop_in->csa_save_index   = 0 ;
    cloop_in->csa_read_index   = 0 ;
    cloop_in->unread_num       = 0 ;
    return 0;
}

int16_t cloop_push(cloop_t *cloop_in,const uint8_t data_in){

#ifdef CLOOP_USE_MUTEX
    cloop_in->mutex = CLOOP_MUTEX_LOCK ;
#endif

    cloop_in->buf[cloop_in->csa_save_index] = data_in;

    if( ++ cloop_in->unread_num > cloop_in->Deep ){
        
        cloop_in->unread_num --   ;

        (++ cloop_in->csa_read_index); 
        cloop_in->csa_read_index%= cloop_in->Deep;
    }
    cloop_in->csa_save_index++;
    cloop_in->csa_save_index %= cloop_in->Deep ;

#ifdef CLOOP_USE_MUTEX
    cloop_in->mutex = CLOOP_MUTEX_UNLOCK ;
#endif

    return 0;
}

int16_t cloop_pull(cloop_t *cloop_in,uint8_t *out_buf){

    if(cloop_in->unread_num>0){

        out_buf[0]=cloop_in->buf[cloop_in->csa_read_index] ;

        cloop_in->unread_num--     ;

        cloop_in->csa_read_index++;
        cloop_in->csa_read_index %= cloop_in->Deep;

        return (int16_t)cloop_in->unread_num ;

    }else{
        return -2;
    }
}

int16_t cloop_pull_all(cloop_t *cloop_in,uint8_t *out_buf,uint16_t max_len){

    if(cloop_in->unread_num == 0 ) return 0;

    for (int i = 0; i < max_len; i++){
        if(cloop_pull(cloop_in,&out_buf[i])<=0){
            return i+1;
        }
    }
    return max_len;
}


// 重置
uint8_t cloop_reset(cloop_t *cloop_in){

    for (int i = 0; i < cloop_in->Deep; i++){
        cloop_in->buf[i]=0;
    }
    cloop_in->opration_protect = 0 ;
    cloop_in->csa_save_index   = 0 ;
    cloop_in->csa_read_index   = 0 ;
    cloop_in->unread_num       = 0 ;
    return 0;
}
